[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, isClient, isIPageInfoForEntity, IUser, IUserHasId, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import ExtensibleCustomError from 'extensible-custom-error';
  7. import { model as mongooseModel } from 'mongoose';
  8. import {
  9. NextPage, GetServerSideProps, GetServerSidePropsContext,
  10. } from 'next';
  11. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  12. import dynamic from 'next/dynamic';
  13. import Head from 'next/head';
  14. import { useRouter } from 'next/router';
  15. import superjson from 'superjson';
  16. import { Comments } from '~/components/Comments';
  17. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  18. // import { useTranslation } from '~/i18n';
  19. import { PageContentFooter } from '~/components/PageContentFooter';
  20. import { CrowiRequest } from '~/interfaces/crowi-request';
  21. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  22. // import { useIndentSize } from '~/stores/editor';
  23. // import { useRendererSettings } from '~/stores/renderer';
  24. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  25. import { EditorConfig } from '~/interfaces/editor-settings';
  26. import { CustomWindow } from '~/interfaces/global';
  27. import { RendererConfig } from '~/interfaces/services/renderer';
  28. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  29. import { IUserUISettings } from '~/interfaces/user-ui-settings';
  30. import { PageModel, PageDocument } from '~/server/models/page';
  31. import { PageRedirectModel } from '~/server/models/page-redirect';
  32. import { UserUISettingsModel } from '~/server/models/user-ui-settings';
  33. import { useSWRxCurrentPage, useSWRxIsGrantNormalized, useSWRxPageInfo } from '~/stores/page';
  34. import { useRedirectFrom } from '~/stores/page-redirect';
  35. import {
  36. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth, useSelectedGrant,
  37. } from '~/stores/ui';
  38. import loggerFactory from '~/utils/logger';
  39. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  40. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  41. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  42. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  43. import { BasicLayout } from '../components/Layout/BasicLayout';
  44. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  45. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  46. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  47. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  48. import {
  49. useCurrentUser, useCurrentPagePath,
  50. useIsLatestRevision,
  51. useIsForbidden, useIsNotFound, useIsTrashPage, useIsSharedUser,
  52. useIsEnabledStaleNotification, useIsIdenticalPath,
  53. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  54. useHackmdUri,
  55. useIsAclEnabled, useIsUserPage, useIsNotCreatable,
  56. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  57. useIsSlackConfigured, useRendererConfig, useEditingMarkdown,
  58. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage,
  59. } from '../stores/context';
  60. import {
  61. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  62. } from './utils/commons';
  63. // import { useCurrentPageSWR } from '../stores/page';
  64. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  65. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  66. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  67. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  68. const logger = loggerFactory('growi:pages:all');
  69. const {
  70. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage,
  71. } = pagePathUtils;
  72. const { removeHeadingSlash } = pathUtils;
  73. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  74. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  75. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  76. {
  77. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  78. return v?.data != null
  79. && v?.data.toObject != null
  80. && v?.meta != null
  81. && isIPageInfoForEntity(v.meta);
  82. },
  83. serialize: (v) => {
  84. return {
  85. data: superjson.stringify(v.data.toObject()),
  86. meta: superjson.stringify(v.meta),
  87. };
  88. },
  89. deserialize: (v) => {
  90. return {
  91. data: superjson.parse(v.data),
  92. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  93. };
  94. },
  95. },
  96. 'IPageToShowRevisionWithMetaTransformer',
  97. );
  98. const IdenticalPathPage = (): JSX.Element => {
  99. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  100. return <IdenticalPathPage />;
  101. };
  102. const PutbackPageModal = (): JSX.Element => {
  103. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  104. return <PutbackPageModal />;
  105. };
  106. type Props = CommonProps & {
  107. currentUser: IUser,
  108. pageWithMeta: IPageToShowRevisionWithMeta,
  109. // pageUser?: any,
  110. redirectFrom?: string;
  111. // shareLinkId?: string;
  112. isLatestRevision?: boolean
  113. isIdenticalPathPage?: boolean,
  114. isForbidden: boolean,
  115. isNotFound: boolean,
  116. IsNotCreatable: boolean,
  117. // isAbleToDeleteCompletely: boolean,
  118. isSearchServiceConfigured: boolean,
  119. isSearchServiceReachable: boolean,
  120. isSearchScopeChildrenAsDefault: boolean,
  121. isSlackConfigured: boolean,
  122. // isMailerSetup: boolean,
  123. isAclEnabled: boolean,
  124. // hasSlackConfig: boolean,
  125. // drawioUri: string,
  126. hackmdUri: string,
  127. // mathJax: string,
  128. // noCdn: string,
  129. // highlightJsStyle: string,
  130. isAllReplyShown: boolean,
  131. // isContainerFluid: boolean,
  132. editorConfig: EditorConfig,
  133. isEnabledStaleNotification: boolean,
  134. // isEnabledLinebreaks: boolean,
  135. // isEnabledLinebreaksInComments: boolean,
  136. // adminPreferredIndentSize: number,
  137. // isIndentSizeForced: boolean,
  138. disableLinkSharing: boolean,
  139. rendererConfig: RendererConfig,
  140. // UI
  141. userUISettings?: IUserUISettings
  142. // Sidebar
  143. sidebarConfig: ISidebarConfig,
  144. };
  145. const GrowiPage: NextPage<Props> = (props: Props) => {
  146. // const { t } = useTranslation();
  147. const router = useRouter();
  148. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  149. // register global EventEmitter
  150. if (isClient()) {
  151. (window as CustomWindow).globalEmitter = new EventEmitter();
  152. }
  153. // commons
  154. useEditorConfig(props.editorConfig);
  155. useCsrfToken(props.csrfToken);
  156. // UserUISettings
  157. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  158. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  159. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  160. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  161. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  162. // page
  163. useIsLatestRevision(props.isLatestRevision);
  164. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  165. useIsForbidden(props.isForbidden);
  166. useIsNotFound(props.isNotFound);
  167. useIsNotCreatable(props.IsNotCreatable);
  168. useRedirectFrom(props.redirectFrom);
  169. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  170. // useShared();
  171. // useShareLinkId(props.shareLinkId);
  172. useIsSharedUser(false); // this page cann't be routed for '/share'
  173. useIsIdenticalPath(false); // TODO: need to initialize from props
  174. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  175. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  176. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  177. useIsSearchServiceReachable(props.isSearchServiceReachable);
  178. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  179. useIsSlackConfigured(props.isSlackConfigured);
  180. // useIsMailerSetup(props.isMailerSetup);
  181. useIsAclEnabled(props.isAclEnabled);
  182. // useHasSlackConfig(props.hasSlackConfig);
  183. // useDrawioUri(props.drawioUri);
  184. useHackmdUri(props.hackmdUri);
  185. // useMathJax(props.mathJax);
  186. // useNoCdn(props.noCdn);
  187. // useIndentSize(props.adminPreferredIndentSize);
  188. useDisableLinkSharing(props.disableLinkSharing);
  189. useRendererConfig(props.rendererConfig);
  190. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  191. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  192. useIsAllReplyShown(props.isAllReplyShown);
  193. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  194. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  195. // const { data: editorMode } = useEditorMode();
  196. const { pageWithMeta, userUISettings } = props;
  197. let shouldRenderPutbackPageModal = false;
  198. if (pageWithMeta != null) {
  199. shouldRenderPutbackPageModal = _isTrashPage(pageWithMeta.data.path);
  200. }
  201. const pageId = pageWithMeta?.data._id;
  202. useCurrentPageId(pageId);
  203. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  204. useSWRxPageInfo(pageId, undefined, pageWithMeta?.meta); // store initial data
  205. useIsTrashPage(_isTrashPage(pageWithMeta?.data.path ?? ''));
  206. useIsUserPage(isUserPage(pageWithMeta?.data.path ?? ''));
  207. useIsNotCreatable(props.isForbidden || !isCreatablePage(pageWithMeta?.data.path ?? '')); // TODO: need to include props.isIdentical
  208. useCurrentPagePath(pageWithMeta?.data.path);
  209. useCurrentPathname(props.currentPathname);
  210. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  211. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  212. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  213. // sync grant data
  214. useEffect(() => {
  215. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  216. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  217. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  218. useEffect(() => {
  219. const decodedURI = decodeURI(window.location.pathname);
  220. if (isClient() && decodedURI !== props.currentPathname) {
  221. router.replace(props.currentPathname, undefined, { shallow: true });
  222. }
  223. }, [props.currentPathname, router]);
  224. const classNames: string[] = [];
  225. // switch (editorMode) {
  226. // case EditorMode.Editor:
  227. // classNames.push('on-edit', 'builtin-editor');
  228. // break;
  229. // case EditorMode.HackMD:
  230. // classNames.push('on-edit', 'hackmd');
  231. // break;
  232. // }
  233. // if (page == null) {
  234. // classNames.push('not-found-page');
  235. // }
  236. return (
  237. <>
  238. <Head>
  239. {/*
  240. {renderScriptTagByName('drawio-viewer')}
  241. {renderScriptTagByName('mathjax')}
  242. {renderScriptTagByName('highlight-addons')}
  243. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  244. */}
  245. </Head>
  246. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  247. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={props.isContainerFluid}>
  248. <header className="py-0 position-relative">
  249. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  250. </header>
  251. <div className="d-edit-none">
  252. <GrowiSubNavigationSwitcher />
  253. </div>
  254. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  255. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  256. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  257. <div id="content-main" className="content-main grw-container-convertible">
  258. <div className="row">
  259. <div className="col">
  260. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  261. { !props.isIdenticalPathPage && (
  262. <>
  263. <PageAlerts />
  264. { props.isForbidden && <ForbiddenPage /> }
  265. { props.IsNotCreatable && <NotCreatablePage />}
  266. { !props.isForbidden && !props.IsNotCreatable && <DisplaySwitcher />}
  267. {/* <DisplaySwitcher /> */}
  268. <div id="page-editor-navbar-bottom-container" className="d-none d-edit-block"></div>
  269. {/* <PageStatusAlert /> */}
  270. </>
  271. ) }
  272. </div>
  273. </div>
  274. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  275. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  276. <div id="revision-toc-content" className="revision-toc-content"></div>
  277. </div>
  278. </div> */}
  279. </div>
  280. </div>
  281. {/* TODO: Check CSS import */}
  282. <footer className="footer d-edit-none">
  283. {/* TODO: Enable page_list.html */}
  284. {/* TODO: Enable isIdenticalPathPage or useIdenticalPath */}
  285. {/* { !props.isIdenticalPathPage && ( */}
  286. <Comments pageId={pageId} />
  287. {/* )} */}
  288. {/* TODO: Create UsersHomePageFooter conponent */}
  289. { isUsersHomePage(props.currentPathname) && (
  290. <div className="container-lg user-page-footer py-5">
  291. <div className="grw-user-page-list-m d-edit-none">
  292. <h2 id="bookmarks-list" className="grw-user-page-header border-bottom pb-2 mb-3">
  293. <i style={{ fontSize: '1.3em' }} className="fa fa-fw fa-bookmark-o"></i>
  294. Bookmarks
  295. </h2>
  296. <div id="user-bookmark-list" className="page-list">
  297. {/* TODO: No need page-list-container class ? */}
  298. <div className="page-list-container">
  299. {/* <BookmarkList userId={pageContainer.state.creator._id} /> */}
  300. </div>
  301. </div>
  302. </div>
  303. <div className="grw-user-page-list-m mt-5 d-edit-none">
  304. <h2 id="recently-created-list" className="grw-user-page-header border-bottom pb-2 mb-3">
  305. <i id="recent-created-icon" className="mr-1">
  306. {/* <RecentlyCreatedIcon /> */}
  307. </i>
  308. Recently Created
  309. </h2>
  310. <div id="user-created-list" className="page-list">
  311. {/* TODO: No need page-list-container class ? */}
  312. <div className="page-list-container">
  313. {/* <RecentCreated userId={pageContainer.state.creator._id} /> */}
  314. </div>
  315. </div>
  316. </div>
  317. </div>
  318. )}
  319. <PageContentFooter />
  320. </footer>
  321. <UnsavedAlertDialog />
  322. <DescendantsPageListModal />
  323. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  324. </BasicLayout>
  325. </>
  326. );
  327. };
  328. function getPageIdFromPathname(currentPathname: string): string | null {
  329. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  330. }
  331. class MultiplePagesHitsError extends ExtensibleCustomError {
  332. pagePath: string;
  333. constructor(pagePath: string) {
  334. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  335. this.pagePath = pagePath;
  336. }
  337. }
  338. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  339. const req: CrowiRequest = context.req as CrowiRequest;
  340. const { crowi } = req;
  341. const { revisionId } = req.query;
  342. const Page = crowi.model('Page') as PageModel;
  343. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  344. const { pageService } = crowi;
  345. let currentPathname = props.currentPathname;
  346. const pageId = getPageIdFromPathname(currentPathname);
  347. const isPermalink = _isPermalink(currentPathname);
  348. const { user } = req;
  349. if (!isPermalink) {
  350. // check redirects
  351. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  352. if (chains != null) {
  353. // overwrite currentPathname
  354. currentPathname = chains.end.toPath;
  355. props.currentPathname = currentPathname;
  356. // set redirectFrom
  357. props.redirectFrom = chains.start.fromPath;
  358. }
  359. // check whether the specified page path hits to multiple pages
  360. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  361. if (count > 1) {
  362. throw new MultiplePagesHitsError(currentPathname);
  363. }
  364. }
  365. const pageWithMeta: IPageToShowRevisionWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  366. const page = pageWithMeta?.data as unknown as PageDocument;
  367. // populate & check if the revision is latest
  368. if (page != null) {
  369. page.initLatestRevisionField(revisionId);
  370. await page.populateDataToShowRevision();
  371. props.isLatestRevision = page.isLatestRevision();
  372. }
  373. props.pageWithMeta = pageWithMeta;
  374. }
  375. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  376. const req = context.req as CrowiRequest<IUserHasId & any>;
  377. const { user } = req;
  378. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  379. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  380. if (userUISettings != null) {
  381. props.userUISettings = userUISettings.toObject();
  382. }
  383. }
  384. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  385. const req: CrowiRequest = context.req as CrowiRequest;
  386. const { crowi } = req;
  387. const Page = crowi.model('Page') as PageModel;
  388. const { currentPathname } = props;
  389. const pageId = getPageIdFromPathname(currentPathname);
  390. const isPermalink = _isPermalink(currentPathname);
  391. const page = props.pageWithMeta?.data;
  392. if (props.isIdenticalPathPage) {
  393. // TBD
  394. }
  395. else if (page == null) {
  396. props.isNotFound = true;
  397. props.IsNotCreatable = !isCreatablePage(currentPathname);
  398. // check the page is forbidden or just does not exist.
  399. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  400. props.isForbidden = count > 0;
  401. }
  402. else {
  403. props.isNotFound = page.isEmpty;
  404. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  405. if (isPermalink && page.isEmpty) {
  406. props.currentPathname = page.path;
  407. }
  408. // /path/to/page ==> /62a88db47fed8b2d94f30000
  409. if (!isPermalink && !page.isEmpty) {
  410. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  411. if (!isToppage) {
  412. props.currentPathname = `/${page._id}`;
  413. }
  414. }
  415. }
  416. }
  417. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  418. // const req: CrowiRequest = context.req as CrowiRequest;
  419. // const { crowi } = req;
  420. // const UserModel = crowi.model('User');
  421. // if (isUserPage(props.currentPagePath)) {
  422. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  423. // if (user != null) {
  424. // props.pageUser = JSON.stringify(user.toObject());
  425. // }
  426. // }
  427. // }
  428. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  429. const req: CrowiRequest = context.req as CrowiRequest;
  430. const { crowi } = req;
  431. const {
  432. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  433. } = crowi;
  434. props.isSearchServiceConfigured = searchService.isConfigured;
  435. props.isSearchServiceReachable = searchService.isReachable;
  436. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  437. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  438. // props.isMailerSetup = mailService.isMailerSetup;
  439. props.isAclEnabled = aclService.isAclEnabled();
  440. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  441. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  442. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  443. // props.mathJax = configManager.getConfig('crowi', 'app:mathJax');
  444. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  445. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  446. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  447. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  448. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  449. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  450. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  451. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  452. props.editorConfig = {
  453. upload: {
  454. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  455. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  456. },
  457. };
  458. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  459. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  460. props.rendererConfig = {
  461. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  462. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  463. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  464. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  465. plantumlUri: process.env.PLANTUML_URI ?? null,
  466. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  467. // XSS Options
  468. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  469. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  470. tagWhiteList: crowi.xssService.getTagWhiteList(),
  471. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  472. };
  473. props.sidebarConfig = {
  474. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  475. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  476. };
  477. }
  478. /**
  479. * for Server Side Translations
  480. * @param context
  481. * @param props
  482. * @param namespacesRequired
  483. */
  484. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  485. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  486. props._nextI18Next = nextI18NextConfig._nextI18Next;
  487. }
  488. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  489. const req = context.req as CrowiRequest<IUserHasId & any>;
  490. const { user } = req;
  491. const result = await getServerSideCommonProps(context);
  492. // check for presence
  493. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  494. if (!('props' in result)) {
  495. throw new Error('invalid getSSP result');
  496. }
  497. const props: Props = result.props as Props;
  498. if (user != null) {
  499. props.currentUser = user.toObject();
  500. }
  501. try {
  502. await injectPageData(context, props);
  503. }
  504. catch (err) {
  505. if (err instanceof MultiplePagesHitsError) {
  506. props.isIdenticalPathPage = true;
  507. }
  508. else {
  509. throw err;
  510. }
  511. }
  512. await injectUserUISettings(context, props);
  513. await injectRoutingInformation(context, props);
  514. injectServerConfigurations(context, props);
  515. await injectNextI18NextConfigurations(context, props, ['translation']);
  516. return {
  517. props,
  518. };
  519. };
  520. export default GrowiPage;